﻿using System;
using System.ComponentModel;
using System.Windows.Forms;

using Rsdn.SmartApp;

namespace Rsdn.Janus.Framework
{
    internal partial class ProgressForm : Form
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly AsyncOperation _asyncOp;

        /// <exception cref="ArgumentNullException"><paramref name="provider" /> is <c>null</c>.</exception>
        public ProgressForm(IServiceProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            _serviceProvider = provider;

            _asyncOp = AsyncHelper.CreateOperation();

            InitializeComponent();
        }

        /// <summary>
        /// Handles the ControlRemoved event of the _flowLayoutPanel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.ControlEventArgs"/> instance containing the event data.</param>
        private void _flowLayoutPanel_ControlRemoved(object sender, ControlEventArgs e)
        {
            // Note: here is hiding search progess panel
            if (_flowLayoutPanel.Controls.Count == 0)
            {
                Hide();
            }
        }

        /// <summary>
        /// Creates the visualizer.
        /// </summary>
        /// <param name="allowCancel">if set to <c>true</c> [allow cancel].</param>
        /// <returns></returns>
        public IProgressVisualizer CreateVisualizer(bool allowCancel)
        {
            DefaultProgressVisualizer visualizer = null;

			_asyncOp.Send(
				() =>
				{
					visualizer = new DefaultProgressVisualizer(allowCancel);
					_flowLayoutPanel.Controls.Add(visualizer);
				});

			_asyncOp.Post(
				() =>
				{
					if (!Visible)
						ShowDialog(
							_serviceProvider
								.GetRequiredService<IUIShell>()
								.GetMainWindowParent());
				});

			return visualizer;
		}
	}
}